package account

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/spf13/cast"
	"insighttracking/query/dao"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type DeleteAccountByIdApiLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeleteAccountByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteAccountByIdApiLogic {
	hostname, _ := os.Hostname()
	return &DeleteAccountByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteAccountByIdApiLogic) DeleteAccountByIdApi(req *types.IdReq) (resp string, err error) {
	// 判断自己不能删除自己
	accountEntity, err := dao.AccountEntity.WithContext(l.ctx).Where(dao.AccountEntity.AccountID.Eq(req.Id)).First()
	if err != nil {
		return "", err
	}
	if accountEntity.AccountType == 0 {
		l.Logger.Error("管理员不能被删除")
		return "", errors.New("删除失败")
	}
	if accountEntity.AccountID == cast.ToInt64(l.ctx.Value("accountId")) {
		return "", errors.New("自己不能删除自己")
	}
	if _, err = dao.AccountEntity.WithContext(l.ctx).Where(dao.AccountEntity.AccountID.Eq(req.Id)).Delete(); err != nil {
		l.Logger.Errorf("delete account error: %s", err.Error())
		return "", errors.New("删除失败")
	}
	return "操作成功", nil
}
